package com.yhp.service.impl;

import com.yhp.bo.UsersBO;
import com.yhp.enums.Sex;
import com.yhp.mapper.UsersMapper;
import com.yhp.pojo.Users;
import com.yhp.service.UserService;
import com.yhp.utils.DateUtil;
import com.yhp.utils.MD5Utils;
import org.n3r.idworker.Sid;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UsersMapper usersMapper;

    @Resource
    private Sid sid;

    private static final String USER_FACE = "http://122.152.205.72:88/group1/M00/00/05/CpoxxFw_8_qAIlFXAAAcIhVPdSg994.png";

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public boolean queryUserName(String name) {
        Example userExample=new Example(Users.class);
        Example.Criteria criteria = userExample.createCriteria();
        criteria.andEqualTo("username",name);
        Users users = usersMapper.selectOneByExample(userExample);

        return users==null?false:true;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Users regUsers(UsersBO usersBO) {
        Users users = new Users();
        users.setUsername(usersBO.getUserName());
        try {
            users.setPassword(MD5Utils.getMD5Str(usersBO.getPassWord()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        //设置昵称
        users.setNickname(usersBO.getUserName());
        //设置头像
        users.setFace(USER_FACE);
        //设置生日
        users.setBirthday(DateUtil.stringToDate("2000-1-1"));
        //设置性别 1 男  0  女  2  保密
        users.setSex(Sex.man.type);
        //设置id主键
        users.setId(sid.nextShort());

        users.setCreatedTime(new Date());
        users.setUpdatedTime(new Date());
        //保存
        usersMapper.insert(users);

        return users;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public Users login(String username, String passWord) {
        Example userExample=new Example(Users.class);
        Example.Criteria criteria = userExample.createCriteria();
        //这里使用的是类中的属性名
        criteria.andEqualTo("username",username);
        criteria.andEqualTo("password",passWord);

        Users users = usersMapper.selectOneByExample(userExample);

        return users;
    }
}
